<?php
declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Validate;

class Xiaoshoukehu extends BaseController
{
    /**
     * 成功返回
     */
    protected function success($msg = '', $data = null)
    {
        return json([
            'code' => 1,
            'message' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 失败返回
     */
    protected function error($msg = '', $data = null)
    {
        return json([
            'code' => 0,
            'message' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 获取客户列表
     */
    public function getList()
    {
        $page = input('pageNo', 1, 'intval');
        $limit = input('pageSize', 20, 'intval');
        $name = input('name', '');

        $where = [];
        if (!empty($name)) {
            $where[] = ['customer_name|phone1|phone2|email|wechat', 'like', "%{$name}%"];
        }
        
        // 获取当前登录用户 // 老旧token2025 - 已换新
        $user = \app\common\TokenAuth::getUserByToken();
        if (!$user) {
            return json(['code' => 401, 'msg' => '未登录或token已过期']);
        }
        if ($user) {
            // 只显示当前用户负责的客户
            $where[] = ['manager_id', '=', $user['id']];
        }

        $count = Db::name('customer')->where($where)->count();

        $list = Db::name('customer')
            ->where($where)
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();
            
        // 记录日志
        /**
        file_put_contents(__DIR__ . '/log250825/customer_list.log', date('Y-m-d H:i:s') . ' - 查询客户列表: ' . json_encode([
            'params' => ['page' => $page, 'limit' => $limit, 'name' => $name],
            'count' => $count,
            'list_count' => count($list)
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        */
        
        // 返回符合前端期望的数据格式
        return json([
            'code' => 200,
            'msg' => '获取成功',
            'data' => [
                'list' => $list,
                'total' => $count
            ]
        ]);
    }

    /**
     * 添加或编辑客户
     */
    public function doEdit()
    {
        $data = input('post.');

        // 验证数据
        $rule = [
            'customer_name' => 'require',
            'phone1' => 'require|mobile',
            'manager_id' => 'require|number',
            'manager_name' => 'require'
        ];

        $message = [
            'customer_name.require' => '客户姓名不能为空',
            'phone1.require' => '联系电话1不能为空',
            'phone1.mobile' => '联系电话1格式不正确',
            'manager_id.require' => '客户负责人不能为空',
            'manager_id.number' => '客户负责人ID必须为数字',
            'manager_name.require' => '客户负责人姓名不能为空'
        ];

        $validate = Validate::rule($rule)->message($message);
        if (!$validate->check($data)) {
            return $this->error($validate->getError());
        }

        // 如果有电话2，验证格式
        if (!empty($data['phone2']) && !preg_match('/^1[3-9]\d{9}$/', $data['phone2'])) {
            return $this->error('联系电话2格式不正确');
        }

        // 如果有邮箱，验证格式
        if (!empty($data['email']) && !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            return $this->error('邮箱格式不正确');
        }

        if (isset($data['id']) && $data['id'] > 0) {
            // 编辑
            $id = $data['id'];
            unset($data['id']);
            $data['update_time'] = date('Y-m-d H:i:s');
            
            // 确保manager_name与manager_id匹配
            if (!empty($data['manager_id']) && (empty($data['manager_name']) || $data['manager_name'] == '未知用户')) {
                // 根据manager_id查询用户真实姓名
                $manager = Db::name('user')->where('id', $data['manager_id'])->field('realname')->find();
                if ($manager && !empty($manager['realname'])) {
                    $data['manager_name'] = $manager['realname'];
                }
            }
            
            $result = Db::name('customer')->where('id', $id)->update($data);
            if ($result) {
                return $this->success('编辑成功');
            } else {
                return $this->error('编辑失败');
            }
        } else {
            // 添加
            $data['create_time'] = date('Y-m-d H:i:s');
            
            // 确保manager_name与manager_id匹配
            if (!empty($data['manager_id']) && (empty($data['manager_name']) || $data['manager_name'] == '未知用户')) {
                // 根据manager_id查询用户真实姓名
                $manager = Db::name('user')->where('id', $data['manager_id'])->field('realname')->find();
                if ($manager && !empty($manager['realname'])) {
                    $data['manager_name'] = $manager['realname'];
                }
            }
            
            $id = Db::name('customer')->insertGetId($data);
            if ($id) {
                return $this->success('添加成功', ['id' => $id]);
            } else {
                return $this->error('添加失败');
            }
        }
    }

    /**
     * 删除客户
     */
    public function doDelete()
    {
        $ids = input('post.ids', '');
        
        if (empty($ids)) {
            return $this->error('参数错误');
        }
        
        // 处理不同类型的输入
        if (is_numeric($ids)) {
            // 单个ID
            $result = Db::name('customer')->where('id', $ids)->delete();
        } else {
            // 多个ID，逗号分隔的字符串
            $idArr = explode(',', (string)$ids);
            $result = Db::name('customer')->whereIn('id', $idArr)->delete();
        }
        
        if ($result) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }

    /**
     * 获取客户详情
     */
    public function getDetail()
    {
        $id = input('id', 0, 'intval');
        
        if ($id <= 0) {
            return $this->error('参数错误');
        }
        
        $info = Db::name('customer')->where('id', $id)->find();
        
        if ($info) {
            return $this->success('获取成功', $info);
        } else {
            return $this->error('客户不存在');
        }
    }

    /**
     * 获取所有客户负责人
     */
    public function getManagers()
    {
        $list = Db::name('user')
            ->field('id, realname')
            ->where('status', 1)
            ->select()
            ->toArray();
            
        return $this->success('获取成功', $list);
    }
} 